package com.gg.communication.communication.tcp;

import com.gg.communication.communication.BaseCommunication;
import com.gg.communication.exception.LoseLineException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author sakura
 * @since 2025-06-17
 */

public class TcpSocketCommunication extends BaseCommunication {
    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    private TcpServer parent;

    public TcpSocketCommunication(Socket socket, TcpServer parent) throws IOException {
        this.socket = socket;
        this.parent = parent;
        setReceiveListener(parent.receiveListener);
        start();
    }

    @Override
    protected void startCommunication() throws IOException {

        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();
    }

    @Override
    public void doCommunicationSend(byte[] msg, String host, int port) throws IOException {
        if (socket != null && !socket.isClosed()) {
            outputStream.write(msg);
            outputStream.flush();
        } else {
            throw new IOException("Socket is closed");
        }
    }

    @Override
    protected void received() {
        super.received();
    }

    @Override
    public byte[] doReceive() throws Exception {
        byte[] buffer = new byte[4096];
        int bytesRead = inputStream.read(buffer);
        if (bytesRead == -1) {
            close();
            throw new LoseLineException("Connection closed by client");
        }

        byte[] receivedData = new byte[bytesRead];
        System.arraycopy(buffer, 0, receivedData, 0, bytesRead);

        //if (receiveListener != null) {
        //    receiveListener.receive(receivedData);
        //}
        return receivedData;
    }

    @Override
    public void close() throws IOException {
        super.close();
        parent.closeClientSocket(socket);
    }
}
